import { relationalStore } from '@kit.ArkData'
import { userType } from './dataBaseModel/userType'

const STORE_CONFIG = {
  name: 'RDB.db',
  securityLevel: relationalStore.SecurityLevel.S1
}

const SQL_CREATE_TABLE_1 = 'CREATE TABLE IF NOT EXISTS USERS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME NOT NULL, ACCOUNT TEXT NOT NULL, PHONE TEXT NOT NULL, PASSWORD TEXT NOT NULL)';

class contactUserDatabase {
  private contactDataRdbStore: relationalStore.RdbStore

  createNow(context) {
    relationalStore.getRdbStore(context, STORE_CONFIG, (err, store) => {
      if (err) {
        console.error('失败', err);
        return;
      }
      console.info('成功')
      store.executeSql(SQL_CREATE_TABLE_1)
      this.contactDataRdbStore = store;
    })
  }

  // 检查账号是否存在
  checkAccountExists(account: string, callback: (exists: boolean) => void) {
    if (!this.contactDataRdbStore) {
      console.error('Database store is not initialized');
      callback(false);
      return;
    }

    // 创建谓词
    let predicates = new relationalStore.RdbPredicates('USERS').equalTo('ACCOUNT', account);

    // 调用query()方法查找数据，返回一个ResultSet结果集
    this.contactDataRdbStore.query(predicates, ['ACCOUNT'], (err, resultSet) => {
      if (err) {
        console.error(`Failed to query data. Code:${err.code}, message:${err.message}`);
        callback(false);
        return;
      }

      let count: number = resultSet.rowCount;
      if (count > 0) {
        callback(true); // 账号已存在
      } else {
        callback(false); // 账号不存在
      }
      resultSet.close(); // 释放结果集资源
    });
  }

  // 存储注册信息
  saveRegistrationInformation(account: string, phone: string, mima: string, name: string) {
    this.checkAccountExists(account, (exists) => {
      if (exists) {
        console.error('账号已存在，不能注册');
        return;
      }

      // 如果账号不存在，继续注册流程
      let shuJu = {
        'ACCOUNT': account,
        'PHONE': phone,
        'PASSWORD': mima,
        'NAME': name
      };

      this.contactDataRdbStore.insert('USERS', shuJu, (err, rowId) => {
        if (err) {
          console.error('存放数据失败', err);
          // 这里可以回调或者处理数据存放失败的情况
          return;
        }
        console.info('存放数据成功，行ID：', rowId);
        // 这里可以回调或者处理注册成功的情况
      });
    });
  }

  //通过账号密码查询
  checkAccountExistence(account: string, password: string, callback: (user: { exists: boolean; data?: userType }) => void) {
    if (!this.contactDataRdbStore) {
      console.error('Database store is not initialized');
      callback({ exists: false });
      return;
    }

    // 创建谓词
    let predicates = new relationalStore.RdbPredicates('USERS')
      .equalTo('ACCOUNT', account).equalTo('PASSWORD', password);

    // 调用query()方法查找数据，返回一个ResultSet结果集
    this.contactDataRdbStore.query(predicates, ['ID', 'NAME', 'ACCOUNT', 'PHONE', 'PASSWORD'], (err, resultSet) => {
      if (err) {
        console.error(`Failed to query data. Code:${err.code}, message:${err.message}`);
        callback({ exists: false });
        return;
      }

      let count: number = resultSet.rowCount;
      if (count > 0) {
        resultSet.goToFirstRow(); // 移动到第一行
        let idIndex = resultSet.getColumnIndex('ID'); // 获取ID列的索引
        let nameIndex = resultSet.getColumnIndex('NAME');
        let accountIndex = resultSet.getColumnIndex('ACCOUNT');
        let phoneIndex = resultSet.getColumnIndex('PHONE');
        let passwordIndex = resultSet.getColumnIndex('PASSWORD');

        let id = resultSet.getString(idIndex); // 使用字段索引获取ID
        let name = resultSet.getString(nameIndex);
        let account = resultSet.getString(accountIndex);
        let phone = resultSet.getString(phoneIndex);
        let password = resultSet.getString(passwordIndex);
        callback({ exists: true, data: { id, name, account, phone, password } });
      } else {
        callback({ exists: false });
      }
      resultSet.close(); // 释放结果集资源
    })
  }

  //通过手机号查询
  checkPhoneExistence(phone: string, callback: (exists: boolean) => void) {
    if (!this.contactDataRdbStore) {
      console.error('Database store is not initialized');
      callback(false);
      return;
    }

    // 创建谓词
    let predicates = new relationalStore.RdbPredicates('USERS')
      .equalTo('PHONE', phone);

    // 调用query()方法查找数据，返回一个ResultSet结果集
    this.contactDataRdbStore.query(predicates, ['ID', 'PHONE'], (err, resultSet) => {
      if (err) {
        console.error(`Failed to query data. Code:${err.code}, message:${err.message}`);
        callback(false);
        return;
      }

      let count: number = resultSet.rowCount;
      if (count > 0) {
        callback(true);
      } else {
        callback(false);
      }
    });
  }
}

let createUserDatabases = new contactUserDatabase()
export default createUserDatabases